package org.nowcoder.leetcode.twoPointers;

import java.util.HashMap;
import java.util.Map;

/**
 * Title  : 454. 4Sum II
 * Source : https://leetcode.cn/problems/4sum-ii/
 * Author : XrazYang
 * Date   : 2023-08-10
 */
public class LeetCode_454 {
    public int fourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
        //哈希表，将四重循环的朴素解法转为O(n^2)
        int count = 0;
        Map<Integer, Integer> sums = new HashMap<>();
        for (int k : nums1) {
            for (int i : nums2) {
                int sum = k + i;
                sums.put(sum, sums.getOrDefault(sum, 0) + 1);
            }
        }
        for (int k : nums3) {
            for (int i : nums4) {
                count += sums.getOrDefault(-k - i, 0);
            }
        }
        return count;
    }
}
